package com.waimai1.waimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.waimai1.waimai.common.BaseContext;
import com.waimai1.waimai.common.R;
import com.waimai1.waimai.common.Utils;
import com.waimai1.waimai.entity.MhCityid;
import com.waimai1.waimai.entity.MyOrder;
import com.waimai1.waimai.exception.NotErrorException;
import com.waimai1.waimai.service.MHService;
import com.waimai1.waimai.service.MhCityidService;
import com.waimai1.waimai.service.MyOrderService;
import com.waimai1.waimai.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/mahua")
@ResponseBody
public class MahuaController {
    @Autowired
    private MHService MHService;
    @Autowired
    private MhCityidService mhCityidService;
//    @Value("${Hw.notifyUrl}")
    private String notifyUrl;
    @Autowired
    private MyOrderService orderService;
    @Autowired
    public RedisTemplate<String,String> redisTemplate;
    @Autowired
    private UserService userService;
    @GetMapping("/getCity")
    public void getCity()  {
        String time = String.valueOf(new Date().getTime());
        TreeMap<String,Object> argsMap= Utils.getParams();
        Map<String,Object> res=(Map<String, Object>) MHService.getData(argsMap,Utils.mhUrl.get("MH_CITY"),time);
        log.info(res.toString());
        if(res.get("rtnCode").equals("000000")){
            List<MhCityid> cityidList=(List<MhCityid>)res.get("rtnData");
            mhCityidService.saveBatch(cityidList);
        }
    }
    @GetMapping("/getCityId/{cityName}")
    public R<Integer> getCityId(@PathVariable String cityName)  {
        LambdaQueryWrapper<MhCityid> cityLambdaQueryWrapper=new LambdaQueryWrapper<>();
        cityLambdaQueryWrapper.eq(MhCityid::getCityName,cityName);
        MhCityid res=mhCityidService.getOne(cityLambdaQueryWrapper,false);
        if(null==res){
            throw new NotErrorException(1007,"MHcity不存在");
        }
        return R.success(res.getCityId());
    }
    @PostMapping("/getData")
    public R<Object> getData(@RequestBody Map<String, Object> argsMap)  {
        String url=(String)argsMap.get("url");
        argsMap.remove("url");
        String time = String.valueOf(new Date().getTime());
        Map<String,Object> res=(Map<String, Object>) MHService.getData(argsMap,Utils.mhUrl.get(url),time);
        if(!"000000".equals(res.get("rtnCode"))){
            throw new NotErrorException(1008,res.get("rtnCode")+(String)res.get("rtnMsg"));
        }
        return R.success(res.get("rtnData"));
    }
    @PostMapping("/lockSeat")
    public R<Object> LockSeat(@RequestBody Map<String,Object> map) throws UnsupportedEncodingException {
        String time = String.valueOf(new Date().getTime());
        String tradeNo="DY"+map.get("takePhoneNumber").toString().substring(7)+time;

        TreeMap<String,Object> argsMap=Utils.getParams("outId",tradeNo,"showId",map.get("showId"),"buySeats",map.get("buySeats"),"acceptChangeseat","0","callBackUrl",notifyUrl,"phoneNo",map.get("takePhoneNumber"));
        //处理前把showInfo编码
//        argsMap.put("buySeats",URLEncoder.encode(buySeats, "UTF-8"));
        Map<String,Object> res=(Map<String, Object>) MHService.getData(argsMap,Utils.mhUrl.get(map.get("url")),time);
        if(res.get("rtnCode").equals("000000")){
            Map<String,Object> resData=(Map<String,Object>) res.get("data");
            //创建订单和详情单
            MyOrder movieOrder=new MyOrder();
            movieOrder.setAcid(BaseContext.getAcid());
            movieOrder.setCinemaName((String) map.get("cinemaName"));
            movieOrder.setMovieName((String) map.get("movieName"));
            movieOrder.setHallName((String) map.get("hallName"));
            movieOrder.setSeat((String) map.get("seat"));
            movieOrder.setShowTime((String) map.get("showTime"));
            movieOrder.setTicketNumber((Integer) map.get("ticketNumber"));
            movieOrder.setTakePhone((String) map.get("takePhone"));
            movieOrder.setTotalPrice((Double) resData.get("price"));
            movieOrder.setStatus(Utils.STATUS_WAIT_PAY);
            movieOrder.setOutTradeNo(tradeNo);
            movieOrder.setOpenid(BaseContext.getopenId());
            movieOrder.setImgUrl((String) map.get("imgUrl"));
            movieOrder.setHwOrderId((String) resData.get("orderNo"));
            if(orderService.save(movieOrder)){
                //添加延时关单功能
                int delayTime=5*60*1000;
                redisTemplate.opsForZSet().add("cancelOrder",tradeNo,System.currentTimeMillis()+delayTime);
            };
//            手机号和注册的不同，则更新
//            if(!BaseContext.getPhone().equals((String) map.get("takePhone"))){
//                userService.updatePhone(movieOrder);
//            }
            resData.put("time",time);
            resData.put("outTradeNo",tradeNo);
            return R.success(resData);
        }else{
            throw new NotErrorException(1008,res.get("rtnCode")+(String)res.get("rtnMsg"));
        }
    }

    @PostMapping("/notify")
    public R<Object> notify(@RequestBody Map<String, Object> argsMap) throws ParseException, NoSuchFieldException, JsonProcessingException, IllegalAccessException, InstantiationException {
        if (argsMap.containsKey("tickets")) {
            return R.success(MHService.mhDYNotify(argsMap));
        }
        return R.success(MHService.mhPPNotify(argsMap));
    }

    @PostMapping("/searchAndUpdateOrder")
    public R<MyOrder> searchAndUpdateOrder(@RequestBody Map<String, Object> argsMap) {
        String outId = (String) argsMap.get("outId");
        MyOrder order = orderService.getById(outId);
        if (order == null) {
            throw new NotErrorException(1001, "订单不存在");
        }
        return MHService.searchOrder(order);
    }

}
